package com.youyi.yyfilepickerlibrary.core.loader;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import com.youyi.yyfilepickerlibrary.core.model.EssFile;
import java.lang.ref.WeakReference;
import java.util.List;

public class EssMimeTypeCollection implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String ARGS_EXTENSION = "args_extension";
    private static final String ARGS_SORT_TYPE = "args_sort_type";
    public static final int LOADER_ID = 3;
    private EssMimeTypeCallbacks mCallbacks;
    private WeakReference<Context> mContext;
    private LoaderManager mLoaderManager;

    public interface EssMimeTypeCallbacks {
        void onFileLoad(List<EssFile> list);

        void onFileReset();
    }

    @Override // android.support.v4.app.LoaderManager.LoaderCallbacks
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        Context context = this.mContext.get();
        if (context == null) {
            return null;
        }
        return EssMimeTypeLoader.newInstance(context, bundle.getString(ARGS_EXTENSION), bundle.getInt(ARGS_SORT_TYPE));
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (this.mContext.get() != null) {
            this.mCallbacks.onFileLoad(((EssMimeTypeLoader) loader).getEssFileList());
        }
    }

    @Override // android.support.v4.app.LoaderManager.LoaderCallbacks
    public void onLoaderReset(Loader<Cursor> loader) {
        EssMimeTypeCallbacks essMimeTypeCallbacks;
        if (this.mContext.get() != null && (essMimeTypeCallbacks = this.mCallbacks) != null) {
            essMimeTypeCallbacks.onFileReset();
        }
    }

    public void onCreate(FragmentActivity fragmentActivity, EssMimeTypeCallbacks essMimeTypeCallbacks) {
        this.mContext = new WeakReference<>(fragmentActivity);
        this.mLoaderManager = fragmentActivity.getSupportLoaderManager();
        this.mCallbacks = essMimeTypeCallbacks;
    }

    public void onDestroy() {
        this.mLoaderManager.destroyLoader(3);
        this.mCallbacks = null;
    }

    public void load(String str, int i, int i2) {
        Bundle bundle = new Bundle();
        bundle.putString(ARGS_EXTENSION, str);
        bundle.putInt(ARGS_SORT_TYPE, i);
        if (this.mContext.get() == null) {
            this.mLoaderManager.initLoader(i2, bundle, this);
        } else {
            this.mLoaderManager.restartLoader(i2, bundle, this);
        }
    }
}
